package com.aia.prm.service;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.util.Assert;

import com.aia.ilp.domain.SmsLog;
import com.aia.ilp.domain.SmsLogExample;
import com.cfh.ahead.Constant;
import com.cfh.domain.User;
import com.cfh.domain.UserExample;
import com.cfh.domain.UserExample.Criteria;
import com.cfh.util.Tools;

@SuppressWarnings("rawtypes")
public class DefaultServiceImpl extends AbstractDefaultService implements DefaultService {
	private static final Logger logger = Logger.getLogger(DefaultServiceImpl.class);

	public void changePassword(User currentUser, String newPassword) {
		currentUser.setPASSWORD(newPassword);
		getUserDAO().updateByPrimaryKey(currentUser);
	}

	public User getUserByUsernameAndPassword(String username, String password) {
		if (logger.isDebugEnabled()) {
			logger.debug("getUserByUsernameAndPassword(String, String) - start"); //$NON-NLS-1$
		}

		Assert.hasText(username);
		Assert.hasText(password);
		UserExample ue = new UserExample();
		Criteria ct = ue.createCriteria();
		ct.andLOGIN_NAMEEqualTo(username);
		ct.andPASSWORDEqualTo(password);
		List list = getUserDAO().selectByExample(ue);
		if (list != null && list.size() > 0) {
			User returnUser = (User) list.get(0);
			if (logger.isDebugEnabled()) {
				logger.debug("getUserByUsernameAndPassword(String, String) - end"); //$NON-NLS-1$
			}
			return returnUser;
		} else {
			return null;
		}
	}

	private void removeCaptcha() {
		try {
			HttpSession session = ServletActionContext.getRequest().getSession();
			if (session != null) {
				session.setAttribute(Constant.CAPTCHA_SESSION_HOLDER, "");
			}
		} catch (Exception e) {
			logger.warn("removeCaptcha:" + e, e);
		}
	}

	private int sendSMS(String msg, String mobile, String remark, boolean isThrowException) {
		try {
			{// 插入SMSLOG表
				SmsLog smslog = new SmsLog();
				smslog.setSMSLOG_GUID(Tools.GUID());
				smslog.setSMSLOG_DATE(Tools.getToday());
				smslog.setSMSLOG_TIME(Tools.getTime());
				smslog.setSMSLOG_MOBILE(mobile);
				smslog.setSMSLOG_FREETEXT1(remark);
				smsLogDAO.insertSelective(smslog);
			}

			if (logger.isDebugEnabled()) {
				logger.debug("Print SMS>" + msg);
			}

			String sql = "INSERT INTO TT_AIA_SMS_MT (EXTEND_TYPE, SP_SERVICE_CODE, PRIORITY, PARAM_ONE, PARAM_TWO, DESTINATION_ADDR, CONTENT) VALUES (- 1, '03', 9, '0986', 'T04W02', ?, ?)";
			return jdbcTemplate.update(sql, new Object[] { mobile, msg });
		} catch (RuntimeException e) {
			logger.error("发短信失败", e);
			if (isThrowException) {
				throw e;
			} else {
				return 0;
			}
		}

	}

	public void PrmSmsJson(com.aia.prm.web.json.PrmSmsJson action) {
		String verifyCode = "";
		String verifySms = "";
		{
			if (!Tools.hasText(action.getMobile())) {
				action.addActionError("手机号为空");
				return;
			}
		}
		{// 验证次数
			SmsLogExample example = new SmsLogExample();
			example.createCriteria().andSMSLOG_MOBILEEqualTo(action.getMobile());
			int count = 0;
			try {
				count = smsLogDAO.mm_countByExample(example);
			} catch (Exception e) {
				count = 0;
				logger.error(e);
			}
			if (count >= 10) {
				action.addActionError("给该手机号发短信的次数达到上限");
				return;
			}
		}
		// OK, 开始发短信
		{// 生成验证码
			verifyCode = Tools.randSixNumberString();
			verifySms = smsContent(verifyCode);
		}

		{// 插入SMSLOG表
			SmsLog smslog = new SmsLog();
			smslog.setSMSLOG_GUID(Tools.GUID());
			smslog.setSMSLOG_DATE(Tools.getToday());
			smslog.setSMSLOG_TIME(Tools.getTime());
			smslog.setSMSLOG_MOBILE(action.getMobile());
			smslog.setSMSLOG_FREETEXT1(verifyCode);
			smsLogDAO.insertSelective(smslog);
		}

		{// 发短信
			try {
				sendSMS(verifySms, action.getMobile(), "PRM_SMS", true);
			} catch (Exception e) {
				action.addActionError("出错了:" + e);
				return;
			}
			logger.debug("发送手机较验码：" + verifyCode);
		}

	}
	
	private String smsContent(String argCode) {
		String s = "";
		if (argCode == null) {
			s = "";
		} else {
			s = argCode;
		}
		return "感谢您的参与，您的手机验证密码为" + s + "";
	}
}
